﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TerrainGrid : MonoBehaviour {

    public TerrainCell kcell;
    // Use this for initialization

    private TerrainCell[] cells;

    private void Awake()
    {
        var objtar = kcell.gameObject;
        var transformcache = this.transform;
        cells = new TerrainCell[ConfigParam.BLOCKWIDTHCOUNT * ConfigParam.BLOCKHEIGHTCOUNT];
        /*
        for (int i = 0; i < ConfigParam.BLOCKWIDTHCOUNT; i++)
        {
            for (int j = 0; j < ConfigParam.BLOCKHEIGHTCOUNT; j++)
            {
                var ins = GameObject.Instantiate(objtar, transformcache);
                var cell = ins.GetComponent<TerrainCell>();
                ins.name = objtar.name + string.Format("({0},{1})", i, j);
                cells[i * ConfigParam.BLOCKHEIGHTCOUNT + j] = cell;

                cell.Gen(i, j);
                cell.Apply();
            }
        }
        */
        StartCoroutine(CreateCell());
    }

    IEnumerator CreateCell()
    {
        var objtar = kcell.gameObject;
        var transformcache = this.transform;

        for (int i = 0; i < ConfigParam.BLOCKWIDTHCOUNT; i++)
        {
            for (int j = 0; j < ConfigParam.BLOCKHEIGHTCOUNT; j++)
            {
                var ins = GameObject.Instantiate(objtar, transformcache);
                var cell = ins.GetComponent<TerrainCell>();
                ins.name = objtar.name + string.Format("({0},{1})", i, j);
                cells[i * ConfigParam.BLOCKHEIGHTCOUNT + j] = cell;

                cell.Gen(i, j);
                cell.Apply();
                yield return  null;
            }
        }

    }
    
}
